package cn.shop.merchant;

import cn.shop.merchant.config.MySqlInjector;
import cn.shop.utils.EnumConverter;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author 李一涵
 */
@EnableConfigurationProperties
@SpringBootApplication(scanBasePackages = {"cn.shop"})
@MapperScan({"cn.shop.merchant.mapper", "cn.shop.transcation.**.mapper"})
public class ShopMerchantApplication implements WebMvcConfigurer {

	public static void main(String[] args) {
		SpringApplication.run(ShopMerchantApplication.class, args);
	}

	@Bean
	public MybatisPlusInterceptor mybatisPlusInterceptor() {
		MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
		interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
		return interceptor;
	}

	@Bean
	public MySqlInjector mySqlInjector() {
		return new MySqlInjector();
	}

	@Bean
	public RestTemplate restTemplate() {
		RestTemplate template = new RestTemplate();
		/**
		 * 中文乱码问题fix
		 */
		List<HttpMessageConverter<?>> list = template.getMessageConverters();
		for (HttpMessageConverter<?> converter : list) {
			if (converter instanceof StringHttpMessageConverter) {
				((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
				break;
			}
		}
		return template;
	}

	@Override
	public void addFormatters(FormatterRegistry registry) {
		registry.addConverterFactory(new EnumConverter());
	}

}
